package com.pic.mgt.executer;

import java.io.File;
import java.io.IOException;

import com.pic.mgt.file.io.FileBuilder;
import com.pic.mgt.file.io.FileOperation;
import com.pic.mgt.log.IgxLog;
import com.pic.mgt.utils.LogUtils;

public final class SimpleConfirmationFileMaker implements ConfirmationFileMaker {
	public static final String tmpFileOkSuffixString = "_$";
	
	private String confirmationFilenameSuffix;
	private FileBuilder fileBuilder;
	private FileOperation fileOperation;

	@Override
	public void makeConfirmationFile(File targetFile) throws IOException {
		if (null != targetFile) {
			long targetFilesize = targetFile.length();
			File confirmationFile = new File(
					 				targetFile.getAbsolutePath() + 
					 				confirmationFilenameSuffix);
			File confirmationTmpFile = getTmepConfirmationFile(confirmationFile);
			
			synchronized(this.fileBuilder) {
				fileBuilder.append(String.valueOf(targetFilesize));
				try {
					// 建立暫存的 File Ok 檔
					// throws IOException
					fileBuilder.buildFile(confirmationTmpFile);
				} catch (IOException e) {
					// ********************** Log **********************
					LogUtils.error(this, IgxLog.messageDetailsLog,
									"Making tmp confirmation file '"
											+ confirmationTmpFile.getAbsolutePath()
											+ "' failed.", e);
					// ********************** Log **********************
					
					throw e;
				}
			}
			
			// Rename 為 正確的 File Ok 檔
			try {
				this.fileOperation.moveFileToFile(confirmationTmpFile, confirmationFile);
			} catch (IOException e) {
				// ********************** Log **********************
				LogUtils.error(this, IgxLog.messageDetailsLog,
								"Renaming tmp confirmation file '"
										+ confirmationTmpFile.getAbsolutePath()
										+ "' to '" + confirmationFile.getAbsolutePath() +
										"' failed.", e);
				// ********************** Log **********************
				
				throw e;
			}
		}
	}
	
	/**
	 * 取得確認檔的暫存檔
	 * @param confirmationFile
	 * @return
	 */
	public static File getTmepConfirmationFile(File confirmationFile) {
		return new File(confirmationFile.getAbsolutePath() + tmpFileOkSuffixString);
	}
	
	// --- getter and setter ---

	public void setConfirmationFilenameSuffix(String confirmationFilenameSuffix) {
		this.confirmationFilenameSuffix = confirmationFilenameSuffix;
	}

	public void setFileBuilder(FileBuilder fileBuilder) {
		this.fileBuilder = fileBuilder;
	}

	public void setFileOperation(FileOperation fileOperation) {
		this.fileOperation = fileOperation;
	}

}
